package com.carsystem.config;

import cn.hutool.core.map.MapUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class TencentCos {
    //  初始化用户身份信息（secretId, secretKey）。
// SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
    private String secretId;
    private String secretKey;
    //区域地址，可在对象储存介绍中查看
    private String regionAddr;
    //桶名称
    private String bucketName;
    //储存桶的远程地址
    private String remoteAddr;
    //COS客户端
    private COSClient cosClient = null;

    public TencentCos(String secretId, String secretKey, String regionAddr, String bucketName, String remoteAddr){
        this.secretId = secretId;
        this.secretKey = secretKey;
        this.regionAddr = regionAddr;
        this.bucketName = bucketName;
        this.remoteAddr = remoteAddr;

        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(regionAddr));
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        // 这里建议设置使用 https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }

    public Map uploadAvatar(MultipartFile avatar) {
        // 指定文件上传到 COS 上的路径，即对象键。例如对象键为folder/picture.jpg，则表示将文件 picture.jpg 上传到 folder 路径下
        Date time = Calendar.getInstance().getTime();
        String path = "avatar/" + new SimpleDateFormat("yyyy-MM-dd").format(time);
        String key = path+"/" + UUID.randomUUID().toString()+".jpg";
        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            // 设置输入流长度为
            objectMetadata.setContentLength(avatar.getInputStream().available());
            // 设置 Content type, 默认是 application/octet-stream
            objectMetadata.setContentType(avatar.getContentType());
            cosClient.putObject(bucketName, key, avatar.getInputStream(), objectMetadata);
            return MapUtil.builder().
                    put("remoteAddr", regionAddr)
                    .put("key", key).build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //删除头像
    public void deleteAvatar(String key){
        cosClient.deleteObject(bucketName, key);
    }
}
